package com.likan.chqjtgc.service.impl;

import com.google.common.collect.Lists;
import com.likan.chqjtgc.commons.AuthLoginClientConfig;
import com.likan.chqjtgc.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author : liuxinghong
 * @Description :
 * @date: 2020/12/10 18:41
 **/
@Service
@Transactional(rollbackFor = {Exception.class})
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisConnectionFactory connectionFactory;
    @Bean
    public RedisTokenStore tokenStore() {
        return new RedisTokenStore(connectionFactory);
    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean logout(String clientId, String userName) {

        Collection<OAuth2AccessToken> webapps = tokenStore().findTokensByClientIdAndUserName(AuthLoginClientConfig.WEB_APP_CLIENT_ID,userName);
        Collection<OAuth2AccessToken> mobiles = tokenStore().findTokensByClientIdAndUserName(AuthLoginClientConfig.MOBILE_CLIENT_ID,userName);
        ArrayList<OAuth2AccessToken> data = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(mobiles)) {
            data.addAll(mobiles);
        }
        if (!CollectionUtils.isEmpty(webapps)){
            data.addAll(webapps);
        }
        if(!CollectionUtils.isEmpty(data)){
            for(OAuth2AccessToken token : data) {
                tokenStore().removeAccessToken(token);
            }
        }
            return true;
    }
}
